//
//  OAuthViewController.swift
//  weibo
//
//  Created by Fosen on 15/11/28.
//  Copyright © 2015年 fosen. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    @objc private func close(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func defultAccount(){
        
        let jsString = "document.getElementById('userId').value = 'guobo3214792@163.com',document.getElementById('passwd').value = '19911017'"
        //修改js中的语言
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }
    
    //在加载视图的时候
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: .Plain, target: self, action: "defultAccount")
        
        loadOAuthView()
    }

    //MARK: 加载授权网页
    private func loadOAuthView(){
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        if let url = NSURL(string: urlString){
            let request = NSURLRequest(URL: url)
            webView.loadRequest(request)
        }
    
    }
 

}

extension OAuthViewController: UIWebViewDelegate{

    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show()
    
    }

    func webViewDidFinishLoad(webView: UIWebView){
    
        SVProgressHUD.dismiss()
    }
    
    //Bool 协议方法 返回值bool   如果返回ture  持有协议对象  就可以正常工作
    /*<NSMutableURLRequest: 0x7f8052c36800> { URL: https://api.weibo.com/oauth2/authorize?client_id=963019977&redirect_uri=http://www.weibo.com }
    
    //注册
    <NSMutableURLRequest: 0x7f8052cba190> { URL: http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=1ycFDj&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D963019977%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.weibo.com%26from%3D%26with_cookie%3D }
    <NSMutableURLRequest: 0x7f8052de5d30> { URL: http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=1ycFDj&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D963019977%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.weibo.com%26from%3D%26with_cookie%3D }
    
    //登录
    <NSMutableURLRequest: 0x7f8052cd49d0> { URL: https://api.weibo.com/oauth2/authorize }
    
    //授权
    <NSMutableURLRequest: 0x7f8052ccb800> { URL: http://www.weibo.com/?code=3be8bf1f61bfe109b5e5843aacf484b3 }

    */
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        
        //屏蔽到不想加载的网站
        if urlString.hasPrefix("https://api.weibo.com"){
        return true
        }
        if !urlString.hasPrefix("http://www.weibo.com"){
        return false
        
        }
        
        //获取授权码
        guard let query = request.URL?.query else{
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        //获取code   请求token  令牌
//        print(query)
        
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            if error != nil { //网网络请求失败
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("登录成功")
            
            
            self.dismissViewControllerAnimated(true) { () -> Void in
                
                NSNotificationCenter.defaultCenter().postNotificationName(WebSwitchRootVCNotification, object: "welcome")
                
            }
        }
        
        
        return false
    }
    
}
